package indi.zhifa.study2025.oa.admin.facade.dep.impl;

import indi.zhifa.engine.core.common.utils.DtoEntityUtil;
import indi.zhifa.engine.mpenhance.utils.DbDtoEntityUtil;
import indi.zhifa.study2025.oa.admin.facade.dep.IDepFacade;
import indi.zhifa.study2025.oa.dao.po.GenDepartmentEntity;
import indi.zhifa.study2025.oa.model.expose.dep.dto.DepCreateDto;
import indi.zhifa.study2025.oa.model.expose.dep.dto.DepEditDto;
import indi.zhifa.study2025.oa.model.expose.dep.vo.DepTreeNode;
import indi.zhifa.study2025.oa.model.expose.dep.vo.DepVo;
import indi.zhifa.study2025.oa.service.dep.IDepService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


@RequiredArgsConstructor
@Component
public class DepFacadeImpl implements IDepFacade {

    final IDepService mDepService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DepVo addDep(Long pParentId, DepCreateDto pDepCreateDto) {

        GenDepartmentEntity parent = null;
        if (!(pParentId == null || pParentId < 0l)) {
            parent = mDepService.checkMin(pParentId);
        }
        GenDepartmentEntity dep = DbDtoEntityUtil.createFromDto(pDepCreateDto, GenDepartmentEntity.class);
        if (parent != null) {
            dep.setParentId(parent.getId());
            dep.setCodeCascade(parent.getCodeCascade() + "-" + pDepCreateDto.getCode());
        } else {
            dep.setParentId(-1L);
            dep.setCodeCascade(pDepCreateDto.getCode());
        }
        dep = mDepService.create(dep);
        DepVo depVo = DbDtoEntityUtil.createFromDto(dep, DepVo.class);
        return depVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DepVo editDep(Long pId, DepEditDto pDepEditDto) {
        GenDepartmentEntity dep = mDepService.edit(pId, pDepEditDto);
        DepVo rtn = DtoEntityUtil.trans(dep, DepVo.class);
        return rtn;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DepVo delete(Long pId) {
        GenDepartmentEntity dep = mDepService.delete(pId);
        DepVo rtn = DtoEntityUtil.trans(dep, DepVo.class);
        return rtn;
    }

    @Override
    public DepTreeNode getTreeNode(Long pId) {
        return mDepService.getTreeNode(pId);
    }

    @Override
    public DepVo info(Long pId) {
        GenDepartmentEntity dep = mDepService.check(pId);
        DepVo rtn = DtoEntityUtil.trans(dep, DepVo.class);
        return rtn;
    }
}
